const serialport = require('serialport')
const httpServer = require('http').createServer();
const io = require("socket.io")(httpServer);
const config = require('./config')

let com4 = serialport(config.serialport)

let connList = []

let datas = [];

(async () => {
  while (true) {
    await sleep(80)
    let msg = datas.pop()
    if (msg && com4.isOpen) {
      console.log(`执行前端命令：${msg}`)
      com4.write(msg)
    }
  }
})()

let bufs = [];

(async () => {
  let tempBuffer = Buffer.alloc(0)
  while (true) {
    await sleep(10)
    let buf = bufs.pop()
    if (!buf) continue;
    buf = buf.filter(item => item !== 13 && item !== 10)
    tempBuffer = Buffer.concat([tempBuffer, buf])

    do {
      let str = tempBuffer.toString()
      let idx = str.indexOf("E")
      if (idx < 0) break

      str = str.substring(0, idx + 1)
      let temBuf = tempBuffer.slice(0, idx + 1)
      tempBuffer = tempBuffer.slice(idx + 1)

      for (let connListElement of connList) {
        if (connListElement.connected) {
          console.log("发送命令到前端：", str, temBuf)
          connListElement.emit("message", str)
        }
      }

      await sleep(10)
    } while (true)
  }
})()

function sleep(time) {
  return new Promise((resolve, reject) => setTimeout(resolve, time))
}


com4.on("close", () => {
  console.log("com4关闭")
})

com4.on("data", (data) => {
  bufs.unshift(data)
})

let port = config.port || 8099
httpServer.listen(port, () => {
  console.log("服务已启动", port)
});
io.on("connection", (socket) => {
  connList.push(socket)
  console.log(`${socket.id}加入链接,当前链接数：${connList.length}`)

  socket.emit('com4init')

  socket.on("send", msg => {
    datas.unshift(msg)
  })

  socket.on("disconnect", () => {
    let idx = connList.findIndex(item => item.id === socket.id)
    if (idx > -1) {
      connList.splice(idx, 1)
    }
    console.log(`${socket.id}断开链接,当前链接数：${connList.length}`)
  })
})
